package com.example.lte.repo;

import com.example.lte.entity.UserEntity;
import com.example.lte.po.UserData;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * UserRepo
 * JpaRepository jpa标准CRUD用法
 * JpaSpecificationExecutor 多条件动态SQL查询用
 *
 * Java 的类是单继承的，C++ 支持多重继承；
 * 虽然 Java 的类不可以多继承，但是接口可以多继承
 *
 * 本例UserRepo接口同时继承了JpaSpecificationExecutor，JpaRepository
 *
 * @author lzh
 * @date 2020/10/13 - 13:43
 */
@Repository
public interface UserRepo extends JpaSpecificationExecutor<UserEntity>, JpaRepository<UserEntity, Long> {

    //JPA 想实现如Mybatis里面的查询resultmapper，该怎么办
    // 1. 建立查询结果映射bean
    // 2. 使用   @Query
    @Transactional(readOnly = true)
    @Query("select new  com.example.lte.po.UserData(u.account,u.name)  from UserEntity u")
    List<UserData> getUserData();


    @Transactional
    @Modifying(clearAutomatically = true)
    @Query("update  UserEntity set password = '10470C3B4B1FED12C3BAAC014BE15FAC67C6E815' where id in ?1")
    int updateDefaultPassByIds(Long[] ids);

    List<UserEntity> findByNameIsLike(String name);

    UserEntity findByAccount(String account);

    UserEntity findByDdLoginCode(String ddOpenId);

    UserEntity findByAccountAndPassword(String account, String password);

    @Query("SELECT O FROM UserEntity O WHERE O.name = :name1  OR O.name = :name2 ")
    List<UserEntity> findTwoName(@Param("name1") String name1, @Param("name2") String name2);


    @Query(nativeQuery = true, value = "SELECT * FROM user WHERE name = :name1  OR name = :name2 ")
    List<UserEntity> findSQL(@Param("name1") String name1, @Param("name2") String name2);


    @Query("SELECT U FROM UserEntity U ,RoleUserEntity RU WHERE U.id = RU.userId AND RU.roleId = :roleId")
    List<UserEntity> findUsersByRole(@Param("roleId") Long roleId);

    //@Transactional 注解用于提交事务，若没有带上这句，会报事务异常提示。
    //@Modifying(clearAutomatically = true) 自动清除实体里保存的数据
    @Transactional
    @Modifying(clearAutomatically = true)
    @Query("update UserEntity u set u.name = ?1 , u.sex = ?2 where u.id = ?3")
    int updateNameAndSexById(String name, int sex, Long userId);


}
